package org.xqyy.eval.controller;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;
import org.xqyy.eval.exception.BusinessException;
import org.xqyy.eval.exception.SessionTimeoutException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;

/**
 * controller全局异常控制器
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ModelAndView handleException(HttpServletRequest reqest,
                                        HttpServletResponse response, Exception e) throws Exception {
        log.error(e.getMessage(), e);
        if (isAjax(reqest)){
            ModelAndView mav = new ModelAndView(new MappingJackson2JsonView());
            mav.addObject("message","操作失败！");
            return mav;
        }else{
            ModelAndView mav = new ModelAndView("jsp/500");
            return mav;
        }

    }

    /**
     * 处理所有业务异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ModelAndView handleBusinessException(HttpServletRequest reqest,
                                                HttpServletResponse response,BusinessException e){
        log.error(e.getMessage(), e);
        ModelAndView mav = new ModelAndView(new MappingJackson2JsonView());
        mav.addObject("message",e.getMessage());
        return mav;

    }


    @ExceptionHandler(SessionTimeoutException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ModelAndView handleException(HttpServletRequest reqest,
                                        HttpServletResponse response, SessionTimeoutException e) throws Exception {
        log.error(e.getMessage(), e);
        if (isAjax(reqest)){
            ModelAndView mav = new ModelAndView(new MappingJackson2JsonView());
            mav.addObject("message","登陆超时请重新登陆！");
            return mav;
        }else{
            ModelAndView mav = new ModelAndView("jsp/sessiontimeout");
            return mav;
        }

    }

    /**
     * 判断是否是ajax请求
     */
    public static boolean isAjax(HttpServletRequest httpRequest) {
        return (httpRequest.getHeader("X-Requested-With") != null
                && "XMLHttpRequest"
                .equals(httpRequest.getHeader("X-Requested-With").toString()));
    }

}
